import axios from 'axios';
import router from '../router'; // 确保这个路径正确指向您的Vue Router实例
import { ElMessage } from 'element-plus';
// 接口定义
export interface IFunction<T = any> {
  (x?: any): T;
}

export interface IObject<T = any> {
  [key: string]: T;
}

export interface IHttpResponse {
  code: number;
  msg: string;
  data?: any; // 使用可选的data属性，以防API有时不返回数据
  rows?: any[]; // 假设rows是数组类型，具体类型根据实际情况调整
  total?: number; // total也是可选的
}

// 工具函数，从环境变量获取API基础路径
const apiBaseUrl = import.meta.env.VITE_APP_API || 'http://localhost:8085/api';

// 创建Axios实例
const http = axios.create({
  baseURL: apiBaseUrl,
  timeout: 5000 // 根据您的需要设置超时时间
});

// 请求拦截器
http.interceptors.request.use(
  (config) => {
    config.headers['X-Requested-With'] = 'XMLHttpRequest';
    const token = getToken(); // 假设getToken()是获取当前用户Token的方法
    if (token) {
      config.headers['Authorization'] = `Bearer ${token}`;
    }
    if (config.method?.toUpperCase() === 'GET') {
      config.params = { ...config.params, _t: new Date().getTime() };
    }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

// 响应拦截器
http.interceptors.response.use(
  (response) => {
    const httpResponse = response.data;
    if (httpResponse.code === 200) {
      return httpResponse; // 直接返回IHttpResponse格式的数据
    }
    ElMessage.error(httpResponse.msg);
    if (httpResponse.code === 401) {
      redirectLogin();
    }
    return Promise.reject(new Error(httpResponse.msg || 'Error'));
  },
  (error) => {
    const status = error.response?.status || 500;
    ElMessage.error(`请求错误: ${error.message}`);
    if (status === 401) {
      redirectLogin();
    }
    return Promise.reject(new Error(getHttpCodeLabel(status) || '接口错误'));
  }
);

// getToken函数的假设实现，您需要根据实际逻辑替换
function getToken() {
  return 'your-token-here'; // 从本地存储、Vuex或其他状态管理中获取Token
}

// 登录超时重定向函数
const redirectLogin = () => {
  router.replace({ path: '/login' });
};

// 根据状态码获取错误信息的函数
function getHttpCodeLabel(status: number): string {
    const httpCodeLabel: Record<number, string> = {
      400: '请求参数错误',
      401: '未授权，请登录',
      403: '拒绝访问',
      404: '请求地址出错',
      408: '请求超时',
      500: '服务器内部错误',
      502: '网关错误',
      503: '服务不可用',
      504: '网关超时'
    };
    return httpCodeLabel[status] || '未知状态码';
  }

// CRUD API接口封装
export default {
  delete: (path: string, params?: IObject): Promise<IHttpResponse> => {
    return http.delete(path, { data: params });
  },
  get: (path: string, params?: IObject, headers?: IObject): Promise<IHttpResponse> => {
    return http.get(path, { params, headers });
  },
  put: (path: string, data?: IObject, headers?: IObject): Promise<IHttpResponse> => {
    return http.put(path, data, { headers });
  },
  post: (path: string, data?: IObject, headers?: IObject): Promise<IHttpResponse> => {
    return http.post(path, data, { headers });
  }
};